package com.powernode.ssm.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();

    // 存对象（转为 JSON String）
    public void setObject(String key, Object value) {
        try {
            String json = objectMapper.writeValueAsString(value);
            stringRedisTemplate.opsForValue().set(key, json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("对象转 JSON 失败", e);
        }
    }

    // 取对象（从 JSON String 转回对象）
    public <T> T getObject(String key, Class<T> clazz) {
        String json = stringRedisTemplate.opsForValue().get(key);
        if (json == null) {
            return null;
        }
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON 转对象失败", e);
        }
    }

    // 设置带过期时间的对象
    public Boolean setObjectWithExpire(String key, Object value, long timeout, TimeUnit unit) {
        try {
            String json = objectMapper.writeValueAsString(value);
            return stringRedisTemplate.opsForValue().setIfAbsent(key, json, timeout, unit);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("对象转 JSON 失败", e);
        }
    }

    // 重新赋值过期时间
    public void resetObjectWithExpire(String key, Object value, long timeout, TimeUnit unit) {
        try {
            String json = objectMapper.writeValueAsString(value);
            stringRedisTemplate.opsForValue().set(key, json, timeout, unit);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("对象转 JSON 失败", e);
        }
    }

    // 删除
    public void delete(String key) {
        stringRedisTemplate.delete(key);
    }

    // key的键值自增1
    public Long increment(String key) {
        return stringRedisTemplate.opsForValue().increment(key);
    }

    // 设置过期时间
    public void expire(String key, long timeout, TimeUnit unit) {
        stringRedisTemplate.expire(key,timeout,unit);
    }

    // 是否有这个key
    public Boolean hasKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }

}
